package uform.ui.assembler;
import uform.ui.comp.INamedComponent;
import uform.ui.comp.Repeater;
import uform.ui.comp.NamedComponent;
import uform.ui.comp.Field;
import uform.ui.comp.Group;
import uform.ui.comp.Component;
import uform.model.core.Schema;
import uform.ui.comp.Control;
using Types;

class SchemaAssembler extends BaseAssembler<Schema>
{
	override public function assemble(schema : Schema) : Component
	{   
		var group = new Group("");
		for(field in schema.fields())
		{
			var cell = field.cell;
			var component = root.assemble(cell);
			component
				.ifIs(INamedComponent, function(named) {
					named.name = field.name;
				})
				.ifIs(Control, function(control) {
					control.value.setDefault(field.defaultValue);
					control.required.set(!cell.isOptional());
				});
			var f = new Field(field.title, component);
			f.description.text.set(field.description);
			group.add(f);
		}
		
		form.model.onChange.add(function(e) {
			if(e.path != group.path())
				return;
			for(field in Reflect.fields(e.value))
			{
				var control = group.componentByName(field).as(Control);
				if(null == control)
					continue;
				control.value.set(Reflect.field(e.value, field));
			}
		});
		
		return group;
	}	
}